package com.yootk.servlet;

import com.yootk.dbc.DatabaseConnection;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * XML异步数据加载
 */
@WebServlet("/dept.action")
public class DeptServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/xml;charset=UTF-8"); // XML数据响应
        String sql = "SELECT deptno,dname,loc FROM dept"; // 查询SQL语句
        Document document = DocumentHelper.createDocument(); // 创建Document实例
        Element deptsElement = document.addElement("depts"); // 创建根元素
        try {
            PreparedStatement pstmt = DatabaseConnection.getConnection().prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery(); // 数据查询
            while (rs.next()) {
                Element deptElement = deptsElement.addElement("dept"); // 获取dept信息
                deptElement.addElement("deptno").setText(String.valueOf(rs.getLong(1)));
                deptElement.addElement("dname").setText(rs.getString(2));
                deptElement.addElement("loc").setText(rs.getString(3));
            }
            XMLWriter writer = new XMLWriter(resp.getOutputStream()); // XML直接输出
            writer.write(document);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseConnection.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
